package com.mxpio.erp.equipment.controller;

import com.mxpio.erp.common.equipment.entity.Equipment;
import com.mxpio.erp.common.equipment.entity.EquipmentBom;
import com.mxpio.erp.common.equipment.entity.EquipmentEqpBasics;
import com.mxpio.erp.common.equipment.service.EquipmentService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Tag(name = "EquipmentEqpBasicsController", description = "设备(类型)信息")
@RestController
@RequestMapping("/erp/equipment/")
public class EquipmentController {

    @Autowired
    private EquipmentService equipmentService;


    @GetMapping("list")
    @Operation(summary = "设备(类型)信息列表", description = "获取设备(类型)信息列表（无分页）", method = "GET")
    public Result<List<Equipment>> list(@Parameter(description = "查询参数") Criteria criteria) {
        List<Equipment> list = equipmentService.list(Equipment.class, criteria);
        return Result.OK(list);
    }

    @GetMapping("page")
    @Operation(summary = "设备(类型)信息列表", description = "获取设备(类型)信息列表（分页）", method = "GET")
    public Result<Page<Equipment>> page(@Parameter(description = "查询参数") Criteria criteria, @Parameter(description = "每页条数") Integer pageSize, @Parameter(description = "页号") Integer pageNo) {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<Equipment> pageResult = equipmentService.listPage(Equipment.class, page, criteria);
        return Result.OK(pageResult);
    }

    @GetMapping("list/{eqpCode}")
    @Operation(summary = "根据eqpCode获取设备(类型)信息列表", description = "根据eqpCode获取设备(类型)信息列表", method = "GET")
    public Result<Equipment> listById(@PathVariable(name = "eqpCode", required = true) String eqpCode) {
        Equipment equipment = equipmentService.getById(Equipment.class, eqpCode);
        return Result.OK(equipment);
    }

    @RequestMapping("add")
    @Operation(summary = "保存设备(类型)信息", description = "保存设备(类型)信息")
    public Result<Equipment> add(@RequestBody Equipment equipment) {
        equipmentService.save(equipment);
        return Result.OK(equipment);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑设备(类型)信息", description = "编辑设备(类型)信息", method = "PUT")
    public Result<Equipment> edit(@RequestBody Equipment equipment) {
        equipmentService.update(equipment);
        return Result.OK(equipment);
    }

    @DeleteMapping("remove/{eqpCodes}")
    @Operation(summary = "根据eqpCodes删除设备(类型)信息", description = "删除设备(类型)信息,多个id用英文逗号分隔", method = "DELETE")
    public Result<Equipment> remove(@PathVariable(name = "eqpCodes", required = true) String eqpCodes) {
        String[] id = eqpCodes.split(",");
        for (String key : id) {
            equipmentService.delete(Equipment.class, key, new SmartCrudPolicyAdapter() {
                @Override
                public boolean beforeDelete(CrudContext context) {
                    Object o = context.getEntity();
                    if (o instanceof Equipment) {
                        Long count = JpaUtil.linq(EquipmentEqpBasics.class).equal("eqpCode", ((Equipment) o).getEqpCode()).count();
                        if (count>0){
                            return false;//设备被设备台账引用后不能删除
                        }
                        try {
                            JpaUtil.lind(EquipmentBom.class).equal("eqpCode", ((Equipment) o).getEqpCode()).delete();
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    return true;
                }
            });
        }
        return Result.OK();
    }

    @PutMapping("edit_and_sync")
    @Operation(summary = "更新下游设备台账", description = "更新下游设备台账", method = "PUT")
    public Result<String> editAndSync(@RequestBody Equipment equipment) {
        return equipmentService.batchSyncEqpBasics(Stream.of(equipment.getEqpCode()).collect(Collectors.toList()));
    }

    @PutMapping("batch_sync/{eqpCodes}")
    @Operation(summary = "批量更新设备下游设备台账，eqpCodes支持多个设备编码，用英文逗号分隔", description = "批量更新设备下游设备台账，eqpCodes支持多个设备编码，用英文逗号分隔", method = "PUT")
    public Result<String> batchSyncEqpBasics(@Parameter(name="eqpCodes设备编码") @PathVariable(name = "eqpCodes", required = true) String eqpCodes) {
        return equipmentService.batchSyncEqpBasics(Stream.of(eqpCodes.split(",")).collect(Collectors.toList()));
    }

    @PutMapping("all_sync")
    @Operation(summary = "全量更新设备下游设备台账", description = "全量更新设备下游设备台账", method = "PUT")
    public Result<String> allSyncEqpBasics() {
        return equipmentService.batchSyncEqpBasics(null);
    }
}
